package com.chinamsp.codegen.convert.db.dto;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.chinamsp.codegen.convert.db.DbCodeGenUtils;

/**
 * 代码生成 build 上下文
 * @author shifenghu
 *
 */
public class DBCodeGenContextBuilder{
	
	/**
	 * 数据
	 */
	private Map<String, Object> data = new HashMap<>(32);
	
	/**
	 * 属性
	 */
	private List<DBCodeGenProperty> properties = new ArrayList<>(32);

	/**
	 * 属性类型
	 */
	private Set<Class<?>> propertyClasses = new HashSet<>(32);
	
	/**
	 * 走起
	 * @param dbName
	 * @param basePackage
	 */
	public DBCodeGenContextBuilder(String dbName, String basePackage) {
		data.put(DB_NAME, dbName);
		data.put(COPYRIGHT, "代码来源于 chinamsp cloud 自动生成组件");
		data.put(BASE_PACKAGE, basePackage);
		data.put(VERSION, "1.0");
		data.put(AUTHOR, "robot.fenghu");
		data.put(MODEL_NAME, DbCodeGenUtils.ftUpcase(DbCodeGenUtils.fieldToProperty(dbName)));
		data.put(PROPERTIES, properties);
		data.put(PARENT_MODEL_NAME, "BaseModel");
	}
	
	/**
	 * 添加 属性
	 * @param property
	 */
	public void addProperty(DBCodeGenProperty property) {
		propertyClasses.add(property.getJavaType());
		// 计算 引用类型
		properties.add(property);
		// 处理是否 继承父类，当前写死成 id
		if (property.getName().equalsIgnoreCase("id")) {
			property.setExtendParent(true);
		}
	}
	
	/**
	 * 生成上下文
	 * @return
	 */
	public Map<String, Object> build(){
		initOther();
		return data;
	}
	
	/**
	 * 获取class名称
	 * @return
	 */
	public String className() {
		return data.get(MODEL_NAME).toString();
	}
	
	/**
	 * 生成 其他属性
	 */
	private void initOther() {
		final StringBuilder sb = new StringBuilder("\"" + data.get(MODEL_NAME) + "[");
		final StringBuilder importsb = new StringBuilder();
		properties.forEach(pro -> {
			sb.append(String.format("%s=\\\"\" + this.%s() + \"\\\",", pro.getName(), pro.getGetterName()));
		});
		sb.deleteCharAt(sb.length() - 1);
		sb.append("]\"");
		for (Class<?> pc : propertyClasses) {
			if (!pc.getPackage().getName().startsWith(LANG_PACKAGE)) {
				importsb.append(String.format("import %s;\n", pc.getName()));
			}
		}
		data.put(TO_STRING, sb.toString());
		data.put(IMPORT_PACKAGE, importsb.toString());
	}
	
	private static final String DB_NAME = "dbName";
	
	private static final String COPYRIGHT = "copyright";
	
	private static final String VERSION = "version";
	
	private static final String AUTHOR = "author";
	
	private static final String MODEL_NAME = "modelName";
	
	private static final String PARENT_MODEL_NAME = "parentModelName";
	
	private static final String PROPERTIES = "properties";
	
	private static final String TO_STRING = "toString";
	
	private static final String BASE_PACKAGE = "basePackage";
	
	private static final String IMPORT_PACKAGE = "importPackges";
	
	private static final String LANG_PACKAGE = "java.lang";
}
